// **********************************************************
// >> File Name: /home/diabio/project/thread_pool/include/thread_pool.h
// >> Author: diabiolin
// >> Created Time: Tue 29 Apr 2025 09:46:37 AM CST
// >> Description:
// **********************************************************

#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include <unistd.h>
#include <pthread.h>


// 错误码定义
#define THREAD_POOL_SUCCESS        0
#define THREAD_POOL_INVALID_ARG   -1
#define THREAD_POOL_QUEUE_FULL    -2
#define THREAD_POOL_SHUTDOWN      -3
#define THREAD_POOL_TIMEOUT       -4

typedef void (*TASKFUNC)(void* args);

typedef enum {
    THREAD_POOL_IMMEDIATE_SHUTDOWN = 1,  // 立即关闭
    THREAD_POOL_GRACEFUL_SHUTDOWN = 2    // 优雅关闭
} ThreadPoolShutdownMode_t;

// 任务列表
typedef struct ThreadTask_s{
    void (*func)(void *args);
    void *args;
}ThreadTask_t;

// 线程池参数
typedef struct ThreadPool_s{
    pthread_t* threads;           // 保存线程池所有创建的所有线程
    int threadMaxNum;            // 最大可创建线程数
    int threadStartNum;          // 启动的线程数
    int threadWaitNum;           // 处于等待中的线程数

    ThreadTask_t* taskQueue;     // 等待执行的任务队列 (循环队列)
    int taskQueueSize;          // 任务队列大小
    int taskQueueHead;          // 当前任务队列头索引
    int taskQueueTail;          // 当前任务队列尾索引
    int taskWaitNum;            // 等待执行的任务个数
    int taskRunningNum;         // 正在执行的任务数量

    pthread_mutex_t mutex;      // 线程池互斥锁
    pthread_cond_t cond;        // 线程池同步信号
    int shutdownMode;           // 关闭模式
    int isExit;                // 线程池是否要关闭
}ThreadPool_t;

// 函数声明
ThreadPool_t* threadPoolCreate(int threadMaxNum, int threadStartNum, int taskQueueSize);
int threadPoolAddTask(ThreadPool_t* threadPool, TASKFUNC taskfunc, void* args);
int threadPoolDestroy(ThreadPool_t* threadPool);
int threadPoolGracefulDestroy(ThreadPool_t* threadPool);
int threadPoolGetTaskCount(ThreadPool_t* threadPool, int* waiting, int* running);
int threadPoolIsShutdown(ThreadPool_t* threadPool);

#endif